from django.shortcuts import render
from django.views import View
from django_redis import get_redis_connection
from django.http import JsonResponse
from rest_framework.generics import CreateAPIView
import random, json
from rest_framework.viewsets import ModelViewSet
from celery_tasks.sms.tasks import send_sms_celery
from user.serializers import UserSerializer, UserInfoModelSerializer
from user.models import User


# Create your views here.

# 获取短信验证码
class SMSCodes(View):

    def get(self, request, mobile):
        redis_conn = get_redis_connection('verify_code')

        send_falg = redis_conn.get('send_falg_%s' % mobile)
        if send_falg != None:
            return JsonResponse({'success': False})

        data = '%06d' % random.randint(0, 999999)
        send_sms_celery.delay(mobile, data)

        p = redis_conn.pipeline()
        p.setex('send_falg_%s' % mobile, 60, 1)
        p.setex('sms_%s' % mobile, 300, data)
        p.execute()

        return JsonResponse({
            'success': True,
            'sms_code': data,
            'message': 'ok'
        })


# 注册
class UserView(CreateAPIView):
    queryset = User.objects.all()
    serializer_class = UserSerializer


# 个人中心
# GET path /user/
class UserInfoModelApiView(ModelViewSet):
    serializer_class = UserInfoModelSerializer
    queryset = User.objects.all()
    def get_object(self):
        return self.request.user

